package com.web.controller;

import com.bean.学生情况;
import com.jdbc.DataSourceTool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/StuExcelServlet")
public class StuExcelServlet extends HttpServlet{
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
            throws ServletException, IOException {

        response.setHeader("Content-Encoding", "gb2312");
        response.setContentType("application/vnd.ms-excel;charset=gb2312");
        PrintWriter out = response.getWriter();

        Connection connection = DataSourceTool.getConnection();
        //定义sql
        String sql = "select * from 学生情况;";
        out.println("学号\t姓名\t性别\t出生日期\t生源地\t院系代号\t政治面貌\t是否住宿\t宿舍电话\t照片");
        //创建sql对象
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            //执行sql
            ResultSet rs = ps.executeQuery();
            //遍历结果集
            while(rs.next()){
                //创建一个学生情况类型的数据用于获取数据库中相同类型的数据
                学生情况 stu=new 学生情况();
                stu.set学号(rs.getString(1));
                stu.set姓名(rs.getString(2));
                stu.set性别(rs.getString(3));
                stu.set出生日期(rs.getString(4));
                stu.set生源地(rs.getString(5));
                stu.set院系代号(rs.getString(6));
                stu.set政治面貌(rs.getString(7));
                stu.set是否住宿(rs.getInt(8));
                stu.set宿舍电话(rs.getString(9));
                stu.set照片(rs.getString(10));

                //把查询结果输出到excel中
                out.print(stu.get学号()+"\t"+stu.get姓名()+"\t"+stu.get性别()+"\t"+stu.get出生日期()+"\t"+stu.get生源地()
                        +"\t"+stu.get院系代号()+"\t"+stu.get政治面貌()+"\t"+stu.get是否住宿()+"\t"+stu.get宿舍电话());
                out.println();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭链接
            DataSourceTool.closeConnection(connection);
        }

    }
}
